package com.example.service.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.client.CourseClient;
import com.example.client.TeacherClient;
import com.example.common.dto.PageDto;
import com.example.common.vo.PageVo;
import com.example.common.vo.Result;
import com.example.entity.dto.EvaluationDto;
import com.example.entity.vo.CourseVo;
import com.example.entity.vo.EvaluationVo;
import com.example.entity.vo.TeacherEvaluationVo;
import com.example.entity.vo.TeacherVo;
import com.example.service.pojo.Evaluation;
import com.example.service.service.EvaluationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Tag(name = "评教管理")
@RequestMapping("/evaluation")
@RequiredArgsConstructor
public class EvaluationController {

    private final EvaluationService evaluationService;

    private final TeacherClient teacherClient;

    private final CourseClient courseClient;

    @GetMapping("{evaluationId}")
    @Operation(summary = "根据id查询评教信息")
    public Result<EvaluationVo> getEvaluationServiceById(@PathVariable String evaluationId){
        Evaluation evaluation = evaluationService.getById(evaluationId);
        EvaluationVo evaluationVo = new EvaluationVo();
        BeanUtils.copyProperties(evaluation, evaluationVo);
        return Result.success(evaluationVo);
    }

    @PostMapping
    @Operation(summary = "添加评教信息")
    public Result<Boolean> addEvaluationService(@RequestBody EvaluationDto evaluationDto){
        Evaluation evaluation = new Evaluation();
        BeanUtils.copyProperties(evaluationDto, evaluation);
        boolean save = evaluationService.save(evaluation);
        return Result.success(save);
    }

    @DeleteMapping("{evaluationId}")
    @Operation(summary = "根据id删除评教信息")
    public Result<Boolean> deleteEvaluationServiceById(@PathVariable String evaluationId){
        boolean remove = evaluationService.removeById(evaluationId);
        return Result.success(remove);
    }

    @PutMapping
    @Operation(summary = "修改评教信息")
    public Result<Boolean> updateEvaluationService(@RequestBody EvaluationDto evaluationDto){
        Evaluation evaluation = new Evaluation();
        BeanUtils.copyProperties(evaluationDto, evaluation);

        boolean update = evaluationService.updateById(evaluation);
        return Result.success(update);
    }

    @PostMapping("page")
    @Operation(summary = "分页查询评教信息")
    public Result<PageVo<TeacherEvaluationVo>> getEvaluationServicePage(@RequestBody PageDto<EvaluationDto> pageDto){
        if(pageDto==null){
            return Result.clientFail("分页参数不能为空", null);
        }
        Page<Evaluation> page = Page.of(pageDto.getPageNum(), pageDto.getPageSize());
        QueryWrapper<Evaluation> wrapper = new QueryWrapper();
        wrapper.select("teacher_id","course_id", "AVG(score) as avgScore");

        if(!StrUtil.isBlankIfStr(pageDto.getQuery().getTeacherName())){
            Result<List<Integer>> teacherIds = teacherClient.getTeacherIdsByName(pageDto.getQuery().getTeacherName());
            if(teacherIds.getData()!=null&& !teacherIds.getData().isEmpty()){
                wrapper.in("teacher_id", teacherIds.getData());
            }
        }
        wrapper.groupBy("teacher_id","course_id");
        page = evaluationService.page(page, wrapper);
        List<Evaluation> records = page.getRecords();
        System.out.println(records);
        List<TeacherEvaluationVo> collect = records.stream().map(evaluation -> {
            TeacherEvaluationVo teacherEvaluationVo = new TeacherEvaluationVo();

            teacherEvaluationVo.setAvgScore(evaluation.getAvgScore());
            Integer teacherId = evaluation.getTeacherId();
            Integer courseId = evaluation.getCourseId();
            if(teacherId==null) {
                System.out.println("出错了,有评教信息对应的老师不存在");
            }else{
                Result<TeacherVo> teacherResult = teacherClient.getTeacherById(teacherId);
                if(teacherResult.getCode()!=Result.SUCCESS_CODE)throw new RuntimeException("远程调用教师服务出现问题");
                teacherEvaluationVo.setTeacherName(teacherResult.getData().getName());
                teacherEvaluationVo.setTeacherNo(teacherResult.getData().getNo());
            }
            if(courseId==null){
                System.out.println("出错了,有评教信息对应的课程不存在");
            }else{
                Result<CourseVo> courseResult = courseClient.getCourseById(courseId);
                if(courseResult.getCode()!=Result.SUCCESS_CODE)throw new RuntimeException("远程调用课程服务出现问题");
                teacherEvaluationVo.setCourseName(courseResult.getData().getName());
                teacherEvaluationVo.setCourseNo(courseResult.getData().getNo());
            }
            return teacherEvaluationVo;
        }).collect(Collectors.toList());
        PageVo<TeacherEvaluationVo> pageVo = new PageVo<>(page.getTotal(), collect);
        return Result.success(pageVo);
    }


}
